<template>
  <div class="business-container">
    <!-- 搜索 -->
    <div class="formSearch">
      <el-form :inline="true" :model="searchData">
        <el-form-item label="商家名称">
          <el-input v-model="searchData.shopName" maxlength="20" placeholder="请输入商家名称" />
        </el-form-item>
        <el-form-item label="注册手机号">
          <el-input v-model="searchData.shopPhone" maxlength="11" placeholder="请输入注册手机号" />
        </el-form-item>
        <el-form-item label="合同状态">
          <el-select v-model="searchData.contractState" clearable placeholder="请选择" style="width: 120px">
            <el-option label="有效" :value="1" />
            <el-option label="无效" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button type="success" @click="handleAdd">新建商家</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading.table"
      :data="tableData"
      border
      :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
      tooltip-effect="dark"
      :style="{ width: '100%' }"
      class="dataTable"
    >
      <el-table-column label="商家名称" show-overflow-tooltip>
        <template #default="scope">{{ scope.row.shopName }}</template>
      </el-table-column>
      <el-table-column prop="shopPhone" label="注册手机号" />
      <el-table-column label="店铺状态">
        <template #default="scope">
          <el-tag :type="scope.row.state === 1 ? 'success' : 'info'">
            {{ scope.row.state === 1 ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="商家启用状态">
        <template #default="scope">
          <el-tag :type="scope.row.businessState === 1 ? 'success' : 'danger'">
            {{ scope.row.businessState === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="保证金上缴状态">
        <template #default="scope">
          <el-tag :type="scope.row.bondState === 1 ? 'success' : 'info'">
            {{ scope.row.bondState === 1 ? '已缴纳' : '未缴纳' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="合同状态">
        <template #default="scope">
          <el-tag :type="scope.row.contractState === 1 ? 'success' : 'danger'">
            {{ scope.row.contractState === 1 ? '有效' : '无效' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作">
        <template #default="scope">
          <div class="btnList">
            <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link type="primary" @click="handleToggleState(scope.row)">
              {{ scope.row.state === 1 ? '停用' : '启用' }}
            </el-button>
            <el-button link type="primary" @click="handleViewDetails(scope.row)">查看</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)">注销</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="searchData.page"
      v-model:page-size="searchData.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      background
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新建/编辑商家弹框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="userState?'修改商家':'新增商家'"
      width="35%"
      :align-center="true"
      center
      :close-on-click-modal="false"
      @closed="onClosed"
    >
      <div>
        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="120px"
        >
          <el-tabs v-model="activeName">
            <el-tab-pane label="授权信息" name="first">
              <el-form-item label="店铺名称" prop="shopName">
                <el-input
                  v-model="formData.shopName"
                  maxlength="20"
                />
              </el-form-item>
              <el-form-item label="店铺负责人" prop="chargePersonName">
                <el-input
                  v-model="formData.chargePersonName"
                  maxlength="20"
                />
              </el-form-item>
              <el-form-item label="负责人电话" prop="chargePersonPhone">
                <el-input
                  v-if="cpPhoneShow"
                  :model-value="hidden(formData.chargePersonPhone, 3, 4)"
                  maxlength="11"
                  @focus="focuscpPhoneInput"
                />
                <el-input
                  v-else
                  ref="phoneRef"
                  v-model="formData.chargePersonPhone"
                  maxlength="11"
                  clearable
                />
              </el-form-item>
              <el-form-item label="店铺地址" prop="shopAdress">
                <el-input
                  v-model="formData.shopAdress"
                  maxlength="60"
                />
              </el-form-item>
              <el-form-item label="生效日期" prop="effectiveDate">
                <el-date-picker
                  v-model="formData.effectiveDate"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  type="date"
                  placeholder="选择日期"
                />
              </el-form-item>
              <el-form-item label="生效年限" prop="effectiveYear">
                <el-input
                  v-model="formData.effectiveYear"
                  type="text"
                  placeholder="请输入内容"
                  maxlength="4"
                  class="elipt"
                  style="width: 50%"
                  show-word-limit
                />
                <span class="year">年</span>
              </el-form-item>
              <el-form-item label="合同状态" prop="contractState">
                <el-radio-group v-model="formData.contractState">
                  <el-radio :label="1">有效 </el-radio>
                  <el-radio :label="0">无效 </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="直播间审核" prop="auditLive">
                <el-radio-group v-model="formData.auditLive">
                  <el-radio :label="1">开启 </el-radio>
                  <el-radio :label="0">关闭 </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="直播间商品审核" prop="auditLiveProduct">
                <el-radio-group v-model="formData.auditLiveProduct">
                  <el-radio :label="1">开启 </el-radio>
                  <el-radio :label="0">关闭 </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="客户信息" name="second">
              <el-form-item label="账号" prop="shopPhone">
                <el-input
                  v-if="shopPhoneShow"
                  :model-value="hidden(formData.shopPhone, 3, 4)"
                  maxlength="20"
                  @focus="focusShopPhoneInput"
                />
                <el-input
                  v-else
                  ref="accountRef"
                  v-model="formData.shopPhone"
                  maxlength="20"
                />
              </el-form-item>
              <el-form-item label="密码" prop="shopPassword">
                <el-input
                  v-model="formData.shopPassword"
                  type="password"
                  maxlength="16"
                />
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible=false">取 消</el-button>
          <el-button v-if="activeName == 'first'" type="primary" @click="next">下一步</el-button>
          <el-button v-else type="primary" :loading="submitLoading" @click="addCheck(formRef)">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="detailsVisible" title="商家详情" width="500px">
      <el-form label-width="100px" :model="detailData" disabled>
        <el-form-item label="商家名称">
          <el-input v-model="detailData.shopName" />
        </el-form-item>
        <el-form-item label="注册手机号">
          <el-input v-model="detailData.shopPhone" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="detailData.state">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商家启用状态">
          <el-input :value="detailData.businessState === 1 ? '启用' : '禁用'" readonly />
        </el-form-item>
        <el-form-item label="合同状态">
          <el-radio-group v-model="detailData.contractState">
            <el-radio :label="1">有效</el-radio>
            <el-radio :label="0">无效</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input v-model="detailData.createTime" />
        </el-form-item>
        <el-form-item label="更新时间">
          <el-input v-model="detailData.updateTime" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailsVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { BusinessService } from '@/api/businessApi'
  import { ApiStatus } from '@/utils/http/status'
  import type {
    ShopType,
    ShopGetAllParam,
    ShopSaveParam,
    ShopUpdateParam,
    ShopStartParam
  } from '@/api/model/businessModel'

  // 表格相关
  const loading = ref({
    table: false
  })
  const tableData = ref<ShopType[]>([])
  const total = ref(0)

  // 搜索表单
  const searchData = reactive<ShopGetAllParam>({
    page: 1,
    pageSize: 10,
    shopName: '',
    shopPhone: '',
    contractState: undefined
  })

  // 对话框相关
  const dialogVisible = ref(false)
  const detailsVisible = ref(false)
  const dialogTitle = ref('')
  const isEdit = ref(false)
  const submitLoading = ref(false)
  const activeName = ref('first')
  const userState = ref(0)
  const cpPhoneShow = ref(true) // 是否显示脱敏负责人手机号
  const shopPhoneShow = ref(true) // 是否显示脱敏账号

  // 表单引用
  const formRef = ref(null)
  const accountRef = ref(null)
  const phoneRef = ref(null)

  // 表单数据
  const formData = reactive<ShopSaveParam | ShopUpdateParam>({
    shopName: '', // 店铺名称
    chargePersonName: '', // 店铺负责人
    chargePersonPhone: '', // 负责人电话
    shopAdress: '', // 地址
    effectiveDate: '', // 生效日期
    effectiveYear: '', // 生效年限
    contractState: 1, // 合同状态 1-有效 0-无效
    auditLive: 1,
    auditLiveProduct: 1,
    shopPhone: '', // 账号
    shopPassword: '', // 密码
    state: 1
  })

  // 详情数据
  const detailData = ref<ShopType>({})

  // 隐藏手机号中间四位
  const hidden = (str: string, start: number, length: number) => {
    if (str && str.length > start + length) {
      return str.substring(0, start) + '*'.repeat(length) + str.substring(start + length)
    }
    return str
  }

  // 表单验证规则
  const rules = {
    effectiveYear: [
      { required: true, message: '请输入生效时限', trigger: 'blur' },
    ],
    shopName: [
      { required: true, message: '请输入店铺名称', trigger: 'blur' },
    ],
    chargePersonName: [
      { required: true, message: '请输入店铺负责人', trigger: 'blur' },
    ],
    chargePersonPhone: [
      { required: true, message: '请输入负责人电话', trigger: 'blur' },
      {
        pattern: /^1[3456789]\d{9}$/,
        message: '目前只支持中国大陆的手机号码',
      },
    ],
    shopAdress: [
      { required: true, message: '请输入地址', trigger: 'blur' },
    ],
    contractState: [
      {
        required: true,
        message: '请选择合同状态',
        trigger: 'change',
      },
    ],
    auditLive: [
      {
        required: true,
        message: '请选择状态',
        trigger: 'change',
      },
    ],
    auditLiveProduct: [
      {
        required: true,
        message: '请选择状态',
        trigger: 'change',
      },
    ],
    effectiveDate: [
      {
        required: true,
        message: '请选择日期',
        trigger: 'change',
      },
    ],
    shopPhone: [
      { required: true, message: '请输入账号', trigger: 'blur' },
      {
        pattern: /^1[3456789]\d{9}$/,
        message: '目前只支持中国大陆的手机号码',
      },
    ],
    shopPassword: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      {
        pattern: /^[~!@#$%^&*\-+=_.0-9a-zA-Z]{8,16}$/,
        message: '8-16密码数字英文混合',
      },
    ]
  }

  // 获取商家列表
  const getAll = async () => {
    loading.value.table = true
    try {
      const res = await BusinessService.getAll(searchData)
      if (res.code === ApiStatus.success) {
        tableData.value = res.data.list
        total.value = res.data.total
      } else {
        ElMessage.error(res.message || '获取商家列表失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('获取商家列表失败')
    } finally {
      loading.value.table = false
    }
  }

  // 处理查询
  const search = () => {
    searchData.page = 1
    getAll()
  }

  // 处理分页
  const handleSizeChange = (val: number) => {
    searchData.pageSize = val
    getAll()
  }

  const handleCurrentChange = (val: number) => {
    searchData.page = val
    getAll()
  }

  // 处理新建
  const handleAdd = () => {
    activeName.value = 'first'
    userState.value = 0
    cpPhoneShow.value = false
    shopPhoneShow.value = false
    isEdit.value = false
    // 重置表单
    Object.assign(formData, {
      shopName: '', // 店铺名称
      chargePersonName: '', // 店铺负责人
      chargePersonPhone: '', // 负责人电话
      shopAdress: '', // 地址
      effectiveDate: '', // 生效日期
      effectiveYear: '', // 生效年限
      contractState: 1, // 合同状态 1-有效 0-无效
      auditLive: 1,
      auditLiveProduct: 1,
      shopPhone: '', // 账号
      shopPassword: '', // 密码
      state: 1
    })
    dialogVisible.value = true
  }

  // 对话框关闭
  const onClosed = () => {
    activeName.value = 'first'
    userState.value = 0
    if (formRef.value) {
      formRef.value.resetFields()
    }
  }

  // 负责人电话输入框获取焦点
  const focuscpPhoneInput = () => {
    cpPhoneShow.value = false
    if (phoneRef.value) {
      setTimeout(() => {
        phoneRef.value.focus()
      }, 100)
    }
  }

  // 账号输入框获取焦点
  const focusShopPhoneInput = () => {
    shopPhoneShow.value = false
    if (accountRef.value) {
      setTimeout(() => {
        accountRef.value.focus()
      }, 100)
    }
  }

  // 下一步
  const next = () => {
    formRef.value.validate((valid: boolean) => {
      if (valid) {
        activeName.value = 'second'
      }
    })
  }

  // 新建验证
  const addCheck = (formEl: any) => {
    if (!formEl) return
    formEl.validate((valid: boolean) => {
      if (valid) {
        submitForm()
      }
    })
  }

  // 处理编辑
  const handleEdit = async (row: ShopType) => {
    dialogTitle.value = '编辑商家'
    isEdit.value = true
    // 获取详情
    try {
      const res = await BusinessService.getById({ shopId: row.shopId! })
      if (res.code === ApiStatus.success) {
        Object.assign(formData, res.data)
        dialogVisible.value = true
      } else {
        ElMessage.error(res.message || '获取商家详情失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('获取商家详情失败')
    }
  }

  // 处理查看详情
  const handleViewDetails = async (row: ShopType) => {
    try {
      const res = await BusinessService.getById({ shopId: row.shopId! })
      if (res.code === ApiStatus.success) {
        detailData.value = res.data
        detailsVisible.value = true
      } else {
        ElMessage.error(res.message || '获取商家详情失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('获取商家详情失败')
    }
  }

  // 处理启用/停用
  const handleToggleState = (row: ShopType) => {
    const action = row.state === 1 ? '停用' : '启用'
    ElMessageBox.confirm(`确认要${action}该商家吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        try {
          const params: ShopStartParam = {
            shopId: row.shopId!,
            state: row.state === 1 ? 0 : 1,
            businessUserId: row.businessUserId
          }
          const res = await BusinessService.start(params)
          if (res.code === ApiStatus.success) {
            ElMessage.success(`${action}成功`)
            getAll()
          } else {
            ElMessage.error(res.message || `${action}失败`)
          }
        } catch (error) {
          console.error(error)
          ElMessage.error(`${action}失败`)
        }
      })
      .catch(() => {
        // 取消操作
      })
  }

  // 处理注销
  const handleDelete = (row: ShopType) => {
    ElMessageBox.confirm('确认要注销该商家吗？注销后该商家数据将被清除且无法恢复！', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        try {
          const res = await BusinessService.cleanShop({ shopId: row.shopId! })
          if (res.code === ApiStatus.success) {
            ElMessage.success('注销成功')
            getAll()
          } else {
            ElMessage.error(res.message || '注销失败')
          }
        } catch (error) {
          console.error(error)
          ElMessage.error('注销失败')
        }
      })
      .catch(() => {
        // 取消操作
      })
  }

  // 提交表单
  const submitForm =async () => {
    submitLoading.value = true
    try {
      let res
      if (isEdit.value) {
        // 编辑
        res = await BusinessService.update(formData as ShopUpdateParam)
      } else {
        // 新建
        res = await BusinessService.save(formData as ShopSaveParam)
      }

      if (res.code === ApiStatus.success) {
        ElMessage.success(`${isEdit.value ? '编辑' : '新建'}成功`)
        dialogVisible.value = false
        getAll()
      } else {
        ElMessage.error(res.message || `${isEdit.value ? '编辑' : '新建'}失败`)
      }
    } catch (error) {
      console.error(error)
      ElMessage.error(`${isEdit.value ? '编辑' : '新建'}失败`)
    } finally {
      submitLoading.value = false
    }
  }

  // 初始化
  onMounted(() => {
    getAll()
  })
</script>

<style lang="scss" scoped>
  .business-container {
    padding: 20px;
    background-color: #fff;

    .formSearch {
      margin-bottom: 20px;
      padding: 20px;
      background-color: #f5f7fa;
      border-radius: 4px;
    }

    .dataTable {
      margin-bottom: 20px;
    }

    .btnList {
      display: flex;
      gap: 10px;
    }

    .dialog-footer {
      text-align: right;
    }

    .year {
      margin-left: 10px;
    }
  }

  @media screen and (max-width: $device-phone) {
    .business-container {
      padding: 10px;

      .formSearch {
        padding: 15px;

        :deep(.el-form-item) {
          margin-bottom: 15px;
        }
      }
    }
  }
</style>
